type Task = (...params: any) => void | Promise<void>
/**懒汉
 * @example
 * new LazyMan('煎饼狗子').drink('水').sleep(3000).eat('憨包')
 * // 输出如下
 * // this is 煎饼狗子
 * // 喝喝喝 水
 * // 先睡觉觉
 * // ......在这里等了3000ms
 * // 起床
 * // 吃吃吃 憨包
 */
class LazyMan {
    /**队列 */
    private queue: Task[] = []

    constructor(name: string) {
        this.add(() => console.log('我是 ' + name))
        setTimeout(() => { //利用宏任务的特性，确保同步任务执行完之后才来到这 （这里的同步任务指的是  lazyMan.drink('水').sleep(3000).eat('憨包') 注册事件）
            this.next()
        });
    }
    eat(food: string) {
        this.add(() => console.log('吃吃吃 ' + food))
        return this
    }
    sleep(time: number) {
        this.add(async () => {
            await new Promise<void>(r => setTimeout(() => {
                r()
                console.log(`睡了${time}ms，起床`);
            }, time))
        })
        return this
    }
    drink(thing: string) {
        this.add(() => console.log('喝喝喝 ' + thing))
        return this
    }
    sleepFirst(time: number) {
        this.addFirst(async () => {
            await new Promise<void>(r => setTimeout(() => {
                r()
                console.log(`睡了${time}ms，起床`);
            }, time))
        })
        return this
    }
    /**添加任务到末尾 */
    private add(task: Task) {
        this.queue.push(async () => {
            await task() //等待当前任务执行完后，接着执行下一个任务
            this.next()
        })
    }
    /**添加任务到开头 */
    private addFirst(task: Task) {
        this.queue.unshift(async () => {
            await task() //等待当前任务执行完后，接着执行下一个任务
            this.next()
        })
    }
    /**执行下一个任务 */
    private next() {
        this.queue.shift()?.()
    }
}
export default LazyMan

//其它写法 
class LazyMan2 {
    private queue: Task[] = []
    constructor(name: string) {
        this.addTask(() => console.log('名字是: ' + name))
        setTimeout(() => {
            this.runTask()
        }, 0);
    }
    drink(name: string) {
        this.addTask(() => console.log('喝: ' + name))
        return this
    }
    eat(name: string) {
        this.addTask(() => console.log('吃: ' + name))
        return this
    }
    sleep(time: number) {
        this.addTask(() => {
            return new Promise(async (resolve, reject) => {
                setTimeout(() => {
                    console.log(`睡了 ${time} 秒`);
                    resolve()
                }, time * 1000)
            })
        })
        return this
    }
    private addTask(task: Task) {
        this.queue.push(task)
    }
    private async runTask() {
        const task = this.queue.shift()
        if (task) {
            await task()
            this.runTask()
        }
    }
}